package webSocket.TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(6666);
        System.out.println("Server started");
        for(;;){
            Socket s = ss.accept();
            System.out.println("Client connected"+s.getRemoteSocketAddress());
            var handler = new Handler(s);
            Thread t= new Thread(handler);
            t.start();
        }
    }
}

class Handler implements Runnable{
    private Socket socket;
    public Handler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try(InputStream input = this.socket.getInputStream()){
            try(OutputStream output = this.socket.getOutputStream()){
                handle(input, output);
            }
        }catch (Exception e){
            try {
                this.socket.close();
            } catch (IOException ex) {

            }
            System.out.println("Client disconnected");
        }

    }

    private void handle(InputStream in, OutputStream out) throws IOException {
        var reader = new BufferedReader(new InputStreamReader(in));
        var writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write("hello\r\n");
        writer.flush();
        for(;;){
            String s = reader.readLine();
            if (s.equals("bye")){
                writer.write("bye\r\n");
                writer.flush();
                break;
            }
            writer.write("ok: "+s+" \r\n");
            writer.flush();
        }
    }
}